import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'dart:math' as math;

// 扇形方向枚举
enum FanDirection {
  top,     // 向上
  right,   // 向右
  bottom,  // 向下
  left,    // 向左
  topLeft, // 左上
  topRight,// 右上
  bottomLeft,  // 左下
  bottomRight, // 右下
}

// 改进的扇形渐变组件
class FanGradientWidget extends StatelessWidget {
  final List<Color> colors;
  final double startAngle;
  final double sweepAngle;
  final double size;
  final double innerRadius; // 新增：内圆半径
  final FanDirection? direction;

  const FanGradientWidget({
    Key? key,
    required this.colors,
    this.startAngle = 0,
    this.sweepAngle = math.pi / 2, // 90度扇形
    this.size = 200,
    this.innerRadius = 0, // 默认无内圆
    this.direction, // 可选方向参数
  }) :
        assert(size > 0, 'Size must be positive'),
        assert(innerRadius >= 0, 'Inner radius must be non-negative'),
        assert(innerRadius < size / 2, 'Inner radius must be less than outer radius'),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    // 根据方向计算起始角度
    double calculatedStartAngle = startAngle;
    if (direction != null) {
      calculatedStartAngle = _getStartAngleByDirection(direction!);
    }

    return CustomPaint(
      size: Size(size, size),
      painter: FanGradientPainter(
        colors: colors,
        startAngle: calculatedStartAngle,
        sweepAngle: sweepAngle,
        innerRadius: innerRadius,
      ),
    );
  }

  // 根据方向计算起始角度
  double _getStartAngleByDirection(FanDirection direction) {
    switch (direction) {
      case FanDirection.top:
        return -math.pi / 2; // -90度，向上
      case FanDirection.right:
        return 0; // 0度，向右
      case FanDirection.bottom:
        return math.pi / 2; // 90度，向下
      case FanDirection.left:
        return math.pi; // 180度，向左
      case FanDirection.topLeft:
        return -math.pi * 3 / 4; // -135度，左上
      case FanDirection.topRight:
        return -math.pi / 4; // -45度，右上
      case FanDirection.bottomLeft:
        return math.pi * 3 / 4; // 135度，左下
      case FanDirection.bottomRight:
        return math.pi / 4; // 45度，右上
    }
  }
}

// 改进的自定义画笔
class FanGradientPainter extends CustomPainter {
  final List<Color> colors;
  final double startAngle;
  final double sweepAngle;
  final double innerRadius;

  FanGradientPainter({
    required this.colors,
    required this.startAngle,
    required this.sweepAngle,
    required this.innerRadius,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final outerRadius = math.min(size.width, size.height) / 2;

    // 创建改进的径向渐变
    final gradient = RadialGradient(
      colors: _createBalancedTransparentColors(),
      stops: _createBalancedStops(),
      center: Alignment.center,
      // 调整渐变的起始和结束半径
      radius: 1.0, // 相对半径
    );

    // 创建渐变矩形，考虑内圆半径
    final gradientRect = Rect.fromCircle(
      center: center,
      radius: outerRadius,
    );

    // 创建画笔
    final paint = Paint()
      ..shader = gradient.createShader(gradientRect);

    // 创建扇环路径（扇形减去内圆）
    final path = _createFanRingPath(center, outerRadius);

    // 绘制扇环
    canvas.drawPath(path, paint);
  }

  // 创建扇环路径
  Path _createFanRingPath(Offset center, double outerRadius) {
    final path = Path();

    if (innerRadius <= 0) {
      // 没有内圆，绘制普通扇形
      path.moveTo(center.dx, center.dy);
      path.arcTo(
        Rect.fromCircle(center: center, radius: outerRadius),
        startAngle,
        sweepAngle,
        false,
      );
      path.close();
    } else {
      // 有内圆，绘制扇环
      // 计算起始和结束位置
      final startX = center.dx + outerRadius * math.cos(startAngle);
      final startY = center.dy + outerRadius * math.sin(startAngle);
      final endAngle = startAngle + sweepAngle;
      final endX = center.dx + outerRadius * math.cos(endAngle);
      final endY = center.dy + outerRadius * math.sin(endAngle);

      final innerStartX = center.dx + innerRadius * math.cos(startAngle);
      final innerStartY = center.dy + innerRadius * math.sin(startAngle);
      final innerEndX = center.dx + innerRadius * math.cos(endAngle);
      final innerEndY = center.dy + innerRadius * math.sin(endAngle);

      // 从外圆起始点开始
      path.moveTo(startX, startY);

      // 绘制外圆弧
      path.arcTo(
        Rect.fromCircle(center: center, radius: outerRadius),
        startAngle,
        sweepAngle,
        false,
      );

      // 连接到内圆结束点
      path.lineTo(innerEndX, innerEndY);

      // 绘制内圆弧（反向）
      path.arcTo(
        Rect.fromCircle(center: center, radius: innerRadius),
        endAngle,
        -sweepAngle,
        false,
      );

      // 闭合路径
      path.close();
    }

    return path;
  }

  // 创建平衡的透明度颜色列表
  List<Color> _createBalancedTransparentColors() {
    if (colors.isEmpty) {
      return [Colors.transparent];
    }

    List<Color> transparentColors = [];

    if (colors.length == 1) {
      // 单色情况：基于原始透明度创建渐变
      final baseColor = colors[0];
      final baseOpacity = baseColor.opacity;
      final steps = 6; // 增加步数以获得更平滑的过渡

      for (int i = 0; i < steps; i++) {
        double t = i / (steps - 1);
        // 使用缓动函数，但保持原始透明度作为最大值
        double opacityMultiplier = _easeOutCubic(1.0 - t);
        double finalOpacity = baseOpacity * opacityMultiplier;

        // 保持原始颜色的RGB值，只调整透明度
        transparentColors.add(Color.fromRGBO(
          baseColor.red,
          baseColor.green,
          baseColor.blue,
          finalOpacity,
        ));
      }
    } else {
      // 多色情况：在颜色之间创建平滑插值，保持原始透明度
      final steps = colors.length * 2; // 增加插值点

      for (int i = 0; i < steps; i++) {
        double t = i / (steps - 1);
        Color interpolatedColor = _interpolateColors(colors, t);

        // 使用平滑的透明度曲线，但基于插值后颜色的原始透明度
        double baseOpacity = interpolatedColor.opacity;
        double opacityMultiplier = _easeOutQuad(1.0 - t * 0.7); // 保留更多不透明度
        double finalOpacity = baseOpacity * opacityMultiplier;

        transparentColors.add(Color.fromRGBO(
          interpolatedColor.red,
          interpolatedColor.green,
          interpolatedColor.blue,
          finalOpacity,
        ));
      }

      // 最后添加完全透明的边缘
      final lastColor = colors.last;
      transparentColors.add(Color.fromRGBO(
        lastColor.red,
        lastColor.green,
        lastColor.blue,
        0.0,
      ));
    }

    return transparentColors;
  }

  // 创建平衡的渐变停止点
  List<double> _createBalancedStops() {
    final transparentColors = _createBalancedTransparentColors();
    final count = transparentColors.length;

    List<double> stops = [];

    // 考虑内圆半径的影响
    double innerRatio = 0.0;
    if (innerRadius > 0) {
      // 假设外半径为size/2
      innerRatio = innerRadius / (innerRadius + 100); // 简化计算
    }

    for (int i = 0; i < count; i++) {
      // 使用非线性分布创建更自然的过渡
      double linearStop = i / (count - 1);
      double adjustedStop = innerRatio + (1.0 - innerRatio) * _easeInOutCubic(linearStop);
      stops.add(adjustedStop.clamp(0.0, 1.0));
    }

    return stops;
  }

  // 缓动函数：ease-out cubic
  double _easeOutCubic(double t) {
    double f = t - 1.0;
    return f * f * f + 1.0;
  }

  // 缓动函数：ease-out quad
  double _easeOutQuad(double t) {
    return 1.0 - (1.0 - t) * (1.0 - t);
  }

  // 缓动函数：ease-in-out cubic
  double _easeInOutCubic(double t) {
    if (t < 0.5) {
      return 4.0 * t * t * t;
    } else {
      double f = 2.0 * t - 2.0;
      return 1.0 + f * f * f / 2.0;
    }
  }

  // 颜色插值函数 - 保持原始透明度
  Color _interpolateColors(List<Color> colors, double t) {
    if (colors.length == 1) return colors[0];
    if (t <= 0.0) return colors.first;
    if (t >= 1.0) return colors.last;

    double scaledT = t * (colors.length - 1);
    int index = scaledT.floor();
    double remainder = scaledT - index;

    if (index >= colors.length - 1) {
      return colors.last;
    }

    final color1 = colors[index];
    final color2 = colors[index + 1];

    // 手动插值以保持透明度控制
    return Color.fromRGBO(
      (color1.red + (color2.red - color1.red) * remainder).round(),
      (color1.green + (color2.green - color1.green) * remainder).round(),
      (color1.blue + (color2.blue - color1.blue) * remainder).round(),
      color1.opacity + (color2.opacity - color1.opacity) * remainder,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    if (oldDelegate is FanGradientPainter) {
      return colors != oldDelegate.colors ||
          startAngle != oldDelegate.startAngle ||
          sweepAngle != oldDelegate.sweepAngle ||
          innerRadius != oldDelegate.innerRadius;
    }
    return true;
  }
}

// 改进的多色扇形渐变组件
class MultiColorFanGradient extends StatelessWidget {
  final double size;
  final double innerRadius;

  const MultiColorFanGradient({
    Key? key,
    this.size = 200,
    this.innerRadius = 0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: MultiColorFanPainter(innerRadius: innerRadius),
    );
  }
}

class MultiColorFanPainter extends CustomPainter {
  final double innerRadius;

  MultiColorFanPainter({required this.innerRadius});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final outerRadius = math.min(size.width, size.height) / 2;

    // 绘制多个扇形，每个使用不同颜色
    final colors = [Colors.red, Colors.orange, Colors.yellow, Colors.green, Colors.blue];
    final anglePerSector = (math.pi * 2) / colors.length;

    for (int i = 0; i < colors.length; i++) {
      final startAngle = i * anglePerSector;

      // 创建平衡的径向渐变
      final gradient = RadialGradient(
        colors: _createSmoothGradient(colors[i]),
        stops: [0.0, 0.3, 0.6, 0.85, 1.0],
      );

      final paint = Paint()
        ..shader = gradient.createShader(
          Rect.fromCircle(center: center, radius: outerRadius),
        );

      // 创建扇环路径
      final path = _createFanRingPath(center, outerRadius, startAngle, anglePerSector);

      canvas.drawPath(path, paint);
    }
  }

  // 创建平滑渐变色
  List<Color> _createSmoothGradient(Color baseColor) {
    return [
      baseColor.withOpacity(0.95), // 中心几乎不透明
      baseColor.withOpacity(0.8),
      baseColor.withOpacity(0.5),
      baseColor.withOpacity(0.2),
      baseColor.withOpacity(0.0),  // 边缘透明
    ];
  }

  // 创建扇环路径
  Path _createFanRingPath(Offset center, double outerRadius, double startAngle, double sweepAngle) {
    final path = Path();

    if (innerRadius <= 0) {
      // 普通扇形
      path.moveTo(center.dx, center.dy);
      path.arcTo(
        Rect.fromCircle(center: center, radius: outerRadius),
        startAngle,
        sweepAngle,
        false,
      );
      path.close();
    } else {
      // 扇环
      final endAngle = startAngle + sweepAngle;

      final startX = center.dx + outerRadius * math.cos(startAngle);
      final startY = center.dy + outerRadius * math.sin(startAngle);
      final innerStartX = center.dx + innerRadius * math.cos(startAngle);
      final innerStartY = center.dy + innerRadius * math.sin(startAngle);
      final innerEndX = center.dx + innerRadius * math.cos(endAngle);
      final innerEndY = center.dy + innerRadius * math.sin(endAngle);

      path.moveTo(startX, startY);
      path.arcTo(
        Rect.fromCircle(center: center, radius: outerRadius),
        startAngle,
        sweepAngle,
        false,
      );
      path.lineTo(innerEndX, innerEndY);
      path.arcTo(
        Rect.fromCircle(center: center, radius: innerRadius),
        endAngle,
        -sweepAngle,
        false,
      );
      path.close();
    }

    return path;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    if (oldDelegate is MultiColorFanPainter) {
      return innerRadius != oldDelegate.innerRadius;
    }
    return true;
  }
}



// 可调节扇形渐变组件
class AdjustableFanGradient extends StatefulWidget {
  @override
  _AdjustableFanGradientState createState() => _AdjustableFanGradientState();
}

class _AdjustableFanGradientState extends State<AdjustableFanGradient> {
  double _startAngle = 0;
  double _sweepAngle = math.pi / 2;
  List<Color> _colors = [Colors.purple, Colors.pink];
  FanDirection? _selectedDirection = FanDirection.right;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        FanGradientWidget(
          colors: _colors,
          startAngle: _startAngle,
          sweepAngle: _sweepAngle,
          direction: _selectedDirection,
          size: 250,
        ),
        SizedBox(height: 20),

        // 方向选择按钮
        Text('扇形方向选择', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
        SizedBox(height: 10),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: FanDirection.values.map((direction) {
            return ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: _selectedDirection == direction ? Colors.blue : null,
                foregroundColor: _selectedDirection == direction ? Colors.white : null,
              ),
              onPressed: () => setState(() => _selectedDirection = direction),
              child: Text(_getDirectionName(direction)),
            );
          }).toList(),
        ),

        SizedBox(height: 20),

        // 角度控制滑块（当未选择方向时生效）
        Text('手动角度控制 (方向为null时生效)'),
        Row(
          children: [
            Text('使用方向'),
            Switch(
              value: _selectedDirection != null,
              onChanged: (value) {
                setState(() {
                  _selectedDirection = value ? FanDirection.right : null;
                });
              },
            ),
          ],
        ),

        if (_selectedDirection == null) ...[
          Text('起始角度: ${(_startAngle * 180 / math.pi).toInt()}°'),
          Slider(
            value: _startAngle,
            min: 0,
            max: math.pi * 2,
            onChanged: (value) => setState(() => _startAngle = value),
          ),
        ],

        Text('扇形角度: ${(_sweepAngle * 180 / math.pi).toInt()}°'),
        Slider(
          value: _sweepAngle,
          min: math.pi / 6, // 30度
          max: math.pi * 2, // 360度
          onChanged: (value) => setState(() => _sweepAngle = value),
        ),

        // 颜色选择按钮
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ElevatedButton(
              onPressed: () => setState(() => _colors = [Colors.red, Colors.orange]),
              child: Text('红-橙'),
            ),
            ElevatedButton(
              onPressed: () => setState(() => _colors = [Colors.blue, Colors.cyan]),
              child: Text('蓝-青'),
            ),
            ElevatedButton(
              onPressed: () => setState(() => _colors = [Colors.purple, Colors.pink, Colors.white]),
              child: Text('紫-粉-白'),
            ),
          ],
        ),
      ],
    );
  }

  String _getDirectionName(FanDirection direction) {
    switch (direction) {
      case FanDirection.top:
        return '上';
      case FanDirection.right:
        return '右';
      case FanDirection.bottom:
        return '下';
      case FanDirection.left:
        return '左';
      case FanDirection.topLeft:
        return '左上';
      case FanDirection.topRight:
        return '右上';
      case FanDirection.bottomLeft:
        return '左下';
      case FanDirection.bottomRight:
        return '右下';
    }
  }
}



